package org.jeecg.modules.xl.logicmana.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.xl.common.XlLogUtil;
import org.jeecg.modules.xl.exceltemplate.vo.DeliveryCodeSheet;
import org.jeecg.modules.xl.logicmana.entity.XlCustomerLogisticPackage;
import org.jeecg.modules.xl.logicmana.service.IXlCustomerLogisticPackageService;
import org.jeecg.modules.xl.logicmana.vo.LogisticOrderVO;
import org.jeecg.modules.xl.logicmana.vo.XlCustomerLogisticDetailVO;
import org.jeecg.modules.xl.logicmana.vo.XlCustomerLogisticPackageQuery;
import org.jeecg.modules.xl.order.entity.XlCustomerOrde;
import org.jeecg.modules.xl.order.entity.XlCustomerOrderDetail;
import org.jeecg.modules.xl.order.service.IXlCustomerOrdeService;
import org.jeecg.modules.xl.order.service.IXlCustomerOrderDetailService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: xl_customer_logistic_package
 * @Author: jeecg-boot
 * @Date:   2024-11-11
 * @Version: V1.0
 */
@Api(tags="xl_customer_logistic_package")
@RestController
@RequestMapping("/slt/logicmana")
@Slf4j
public class XlCustomerLogisticPackageController extends JeecgController<XlCustomerLogisticPackage, IXlCustomerLogisticPackageService> {
	@Autowired
	private IXlCustomerLogisticPackageService xlCustomerLogisticPackageService;

	@Autowired
	private IXlCustomerOrdeService xlCustomerOrdeService;


	@Autowired
	private XlLogUtil xlLogUtil ;

	/**
	 * 分页列表查询
	 *
	 * @param xlCustomerLogisticPackage
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "xl_customer_logistic_package-分页列表查询")
	//@ApiOperation(value="xl_customer_logistic_package-分页列表查询", notes="xl_customer_logistic_package-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<LogisticOrderVO>> queryPageList(LogisticOrderVO xlCustomerLogisticPackage,
														@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
														@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
														HttpServletRequest req) {
        QueryWrapper<LogisticOrderVO> queryWrapper = QueryGenerator.initQueryWrapper(xlCustomerLogisticPackage, req.getParameterMap());
//		queryWrapper.select(" order_code , GROUP_CONCAT(DISTINCT CONCAT(`logi_com`, '：', `logi_order`) SEPARATOR ',') AS logi_order, Max(create_time) as create_time ");
//		queryWrapper.groupBy(" order_code ");

		//当前操作人
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		//当前用户的角色
		String roles = user.getRoleCode();

		if (StrUtil.containsAny(roles, "slt_customer")) {//是否是采购人员
			queryWrapper.eq("order_create_by",user.getUsername());
		}

		Page<LogisticOrderVO> page = new Page<>(pageNo, pageSize);

		//IPage<XlCustomerLogisticPackage> pageList = xlCustomerLogisticPackageService.page(page, queryWrapper);
		IPage<LogisticOrderVO> pageList = xlCustomerLogisticPackageService.list2(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 * 订单包裹查询
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/packageList")
	public Result<List<XlCustomerLogisticPackage>> packageList(
																  @RequestParam(name="orderCode") String orderCode,
//																  @RequestParam(name="logiCom") String logiCom,
																  HttpServletRequest req) {
		return Result.OK(xlCustomerLogisticPackageService.list(Wrappers.lambdaQuery(XlCustomerLogisticPackage.class)
				.select(XlCustomerLogisticPackage::getOrderCode,XlCustomerLogisticPackage::getLogiCom,XlCustomerLogisticPackage::getLogiOrder)
			.eq(XlCustomerLogisticPackage::getOrderCode,orderCode)
//			.eq(XlCustomerLogisticPackage::getLogiCom,logiCom)
				.groupBy(XlCustomerLogisticPackage::getOrderCode,XlCustomerLogisticPackage::getLogiCom,XlCustomerLogisticPackage::getLogiOrder)
		));
	}

	/**
	 * 包裹明细查询
	 * @param query
	 * @param req
	 * @return
	 */
	@ApiOperation(value="包裹明细查询", notes="包裹明细查询")
	@GetMapping(value = "/queryDetail")
	public Result<List<XlCustomerLogisticDetailVO>> queryDetail(XlCustomerLogisticPackageQuery query,
																  HttpServletRequest req) {
		List<XlCustomerLogisticDetailVO> detailVOS = xlCustomerLogisticPackageService.queryDetail(query);
		return Result.OK(detailVOS);
	}

	/**
	 *   添加
	 *
	 * @param xlCustomerLogisticPackage
	 * @return
	 */
	@AutoLog(value = "xl_customer_logistic_package-添加")
	@ApiOperation(value="xl_customer_logistic_package-添加", notes="xl_customer_logistic_package-添加")
	@RequiresPermissions("org.jeecg.modules.xl:xl_customer_logistic_package:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody XlCustomerLogisticPackage xlCustomerLogisticPackage) {
		xlCustomerLogisticPackageService.save(xlCustomerLogisticPackage);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param xlCustomerLogisticPackage
	 * @return
	 */
	@AutoLog(value = "xl_customer_logistic_package-编辑")
	@ApiOperation(value="xl_customer_logistic_package-编辑", notes="xl_customer_logistic_package-编辑")
	@RequiresPermissions("org.jeecg.modules.xl:xl_customer_logistic_package:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody XlCustomerLogisticPackage xlCustomerLogisticPackage) {
		xlCustomerLogisticPackageService.updateById(xlCustomerLogisticPackage);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "xl_customer_logistic_package-通过id删除")
	@ApiOperation(value="xl_customer_logistic_package-通过id删除", notes="xl_customer_logistic_package-通过id删除")
	@RequiresPermissions("org.jeecg.modules.xl:xl_customer_logistic_package:delete")
	@DeleteMapping(value = "/delete1")
	public Result<String> delete1(@RequestParam(name="id",required=true) String id) {
		xlCustomerLogisticPackageService.removeById(id);
		return Result.OK("删除成功!");
	}
	@RequiresPermissions("slt:logisticpackagemana:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="orderCode",required=true) String orderCode,@RequestParam(name="logiOrder",required=true) String logiOrder) {
		Map ss= new HashMap();
		ss.put("order_code",orderCode);
		ss.put("logi_order",logiOrder);
		xlCustomerLogisticPackageService.removeByMap(ss);
		//需要更新订单的delivery_codes
		QueryWrapper<XlCustomerLogisticPackage> xlCustomerLogisticPackageQueryWrapper = new QueryWrapper<>();
		xlCustomerLogisticPackageQueryWrapper.eq("order_code",orderCode);
		List<XlCustomerLogisticPackage> xlCustomerLogisticPackages=  xlCustomerLogisticPackageService.list(xlCustomerLogisticPackageQueryWrapper);

		UpdateWrapper<XlCustomerOrde> updateWrapper = new UpdateWrapper<>();
		if(ObjectUtil.isEmpty(xlCustomerLogisticPackages)){
			//物流信息为空
			updateWrapper.set("delivery_codes",null).eq("order_code",orderCode);
		}else{
			String newCodes = xlCustomerLogisticPackages.stream()
					.map(item -> {
						return item.getLogiCom() + ":" + item.getLogiOrder();
					})
					.collect(Collectors.joining(","));
			updateWrapper.set("delivery_codes",newCodes).eq("order_code",orderCode);
		}
		xlCustomerOrdeService.update(updateWrapper);
		return Result.OK("删除成功!");
	}
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "xl_customer_logistic_package-批量删除")
	@ApiOperation(value="xl_customer_logistic_package-批量删除", notes="xl_customer_logistic_package-批量删除")
	@RequiresPermissions("org.jeecg.modules.xl:xl_customer_logistic_package:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.xlCustomerLogisticPackageService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "xl_customer_logistic_package-通过id查询")
	@ApiOperation(value="xl_customer_logistic_package-通过id查询", notes="xl_customer_logistic_package-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<XlCustomerLogisticPackage> queryById(@RequestParam(name="id",required=true) String id) {
		XlCustomerLogisticPackage xlCustomerLogisticPackage = xlCustomerLogisticPackageService.getById(id);
		if(xlCustomerLogisticPackage==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(xlCustomerLogisticPackage);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param xlCustomerLogisticPackage
    */
    @RequiresPermissions("org.jeecg.modules.xl:xl_customer_logistic_package:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, XlCustomerLogisticPackage xlCustomerLogisticPackage) {
        return super.exportXls(request, xlCustomerLogisticPackage, XlCustomerLogisticPackage.class, "xl_customer_logistic_package");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
	//不再维护明细发货
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        //return super.importExcel(request, response, XlCustomerLogisticPackage.class);
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			// 获取上传文件对象
			MultipartFile file = entity.getValue();
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setSheetNum(1);	//只导入一个sheet数据
			params.setStartSheetIndex(0);	//从第一个sheet开始导入
			params.setNeedSave(false);
			try {
				List<DeliveryCodeSheet> list = ExcelImportUtil.importExcel(file.getInputStream(), DeliveryCodeSheet.class, params);

				//判断所有订单是否完全发货，判断依据，订单里的所有明细shipment_state=1

				for(DeliveryCodeSheet orderder:list){
					if(ObjectUtil.isEmpty(orderder.getOrderCode())||ObjectUtil.isEmpty(orderder.getLogiOrder())||ObjectUtil.isEmpty(orderder.getLogiCom())){
						continue;
					}
					QueryWrapper<XlCustomerLogisticPackage> xlCustomerLogisticPackageQueryWrapper = new QueryWrapper<>();
					xlCustomerLogisticPackageQueryWrapper.eq("order_code",orderder.getOrderCode());
					xlCustomerLogisticPackageQueryWrapper.eq("logi_order",orderder.getLogiOrder());

					if(ObjectUtil.isNotEmpty( xlCustomerLogisticPackageService.getOne(xlCustomerLogisticPackageQueryWrapper))){
						continue;//如果这个物流单已经存在，直接跳过
					}
					//构造物流单
					XlCustomerLogisticPackage packEntity = new XlCustomerLogisticPackage();
					packEntity.setOrderCode(orderder.getOrderCode());
					packEntity.setLogiCom(orderder.getLogiCom());
					packEntity.setLogiOrder(orderder.getLogiOrder());
					xlCustomerLogisticPackageService.save(packEntity);
					//更新订单的发货状态，只要导入一个物流包裹，就是已发货（待收货）
					LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
					String loginInfo = orderder.getLogiCom()+":"+orderder.getLogiOrder();
					QueryWrapper<XlCustomerOrde> xlCustomerOrdeQueryWrapper = new QueryWrapper<>();
					xlCustomerOrdeQueryWrapper.eq("order_code",orderder.getOrderCode());
					XlCustomerOrde xlCustomerOrdeTargetTemp =  xlCustomerOrdeService.getOne(xlCustomerOrdeQueryWrapper);
					String fulltext = "";
					if( ObjectUtil.isEmpty(xlCustomerOrdeTargetTemp.getDeliveryCodes())){
						//不存在，并且是第一个物流单，直接设置
						fulltext = loginInfo;
					}
					if( ObjectUtil.isNotEmpty(xlCustomerOrdeTargetTemp.getDeliveryCodes())){
						if(xlCustomerOrdeTargetTemp.getDeliveryCodes().contains(loginInfo)){
							//如果包含就直接赋值
							//其实这一步不需要，应为对于重复的物流单号不会重新导入，看代码行 283～285
							fulltext = xlCustomerOrdeTargetTemp.getDeliveryCodes();
						}else{
							fulltext = loginInfo+","+xlCustomerOrdeTargetTemp.getDeliveryCodes();
						}

					}
					//判断物流单是城市配送还是一件代发
					String deliveryWay = "2";
					if("城市配送".equals(orderder.getLogiCom())||"chengshipeisong".equals(orderder.getLogiCom())||"CSPS".equals(orderder.getLogiCom())){
						deliveryWay = "1";
					}
					UpdateWrapper<XlCustomerOrde> xlCustomerOrdeUpdateWrapper= new UpdateWrapper<>();
					xlCustomerOrdeUpdateWrapper
							.set("delivery_codes",fulltext)
							.set("delivery_way",deliveryWay) //根据导入的物流订单类型，重新更新订单的快递方式
							.eq("order_code",orderder.getOrderCode());
					xlCustomerOrdeService.update(xlCustomerOrdeUpdateWrapper);//先更新deliverycode，

					xlCustomerOrdeUpdateWrapper.set("shipment_state","2")
							.set("shipment_time", DateUtil.now())
							.set("shipment_by",sysUser.getUsername())
							.set("order_status","待收货")
							.eq("order_code",orderder.getOrderCode())
							.eq("order_status","待发货");//再更新shipment_state和order_status

					//为什么要两次更新，因为 更新：delivery_codes 的条件 和  更新发货状态和状态不一样。
					xlCustomerOrdeService.update(xlCustomerOrdeUpdateWrapper);
					xlLogUtil.insertLog(orderder.getOrderCode(),"发货","导入物流信息",new Date(),"待发货","待收货");
				}

				return Result.OK("文件导入成功！数据行数:" + list.size());
			} catch (Exception e) {
				log.error(e.getMessage(),e);
				return Result.error("文件导入失败:"+e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.OK("文件导入失败！");
    }

}
